package com.bytedance.speech.speechdemo

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.media.AudioManager
import android.media.AudioManager.MODE_IN_COMMUNICATION
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import com.bytedance.speech.speechdemo.AudioRecognitionService.TAG
import com.bytedance.speech.speechdemo.settings.Settings
import com.bytedance.speech.speechdemo.volcengine.asr.AsrEngine2
import com.bytedance.speech.speechdemo.volcengine.tts.TtsEngine2
import com.bytedance.speech.speechengine.SpeechEngineDefines
import com.cn.lxz.lot.http.HttpManager


class HttpActivity : BaseActivity() {

    private lateinit var tvLlmAsk: TextView
    private lateinit var audioManager: AudioManager
    private var progressDialog: ProgressDialog?=null
    private lateinit var tvLlm: EditText
    private lateinit var tvAsr: EditText
    private lateinit var mAudioManager: AudioManager
    private lateinit var mAFChangeListener: AudioManager.OnAudioFocusChangeListener
    private var mEngineSwitch: Button? = null
    private var mEngineStatus: TextView? = null
    private var mResult: TextView? = null
    private var mSettings: Settings? = null
    val handler = Handler();

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        // App in background
        Log.i(TAG, "Application becomming background.")
    }

    var tts:TtsEngine2?=null
    var asr = AsrEngine2()
    //是否触发关键字
    var isEventWord = false

    var count = 0;
    var maxCount = 5
    var asrResultText = ""
    var lastAsrText = ""

    var isFrist = true
    var eventWordAnswer = "我在"
    var emptyWordAnswer = "没有什么事情我先退下了"
    var nullWordAnswer = "这个我还不会呢"

    @SuppressLint("ClickableViewAccessibility", "InflateParams", "HardwareIds")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        tvAsr = findViewById<EditText>(R.id.asr_result_text)
        tvLlm = findViewById<EditText>(R.id.llm_result_text)
        tvLlmAsk = findViewById<TextView>(R.id.llm_ask)
        audioManager = getSystemService(AUDIO_SERVICE) as AudioManager
//        audioManager.mode = MODE_IN_COMMUNICATION
//        audioManager.setSpeakerphoneOn(true)
        startASrStream()
    }

    private fun startASrStream() {
        progressDialog=null
        asr = AsrEngine2()
        asr.start(this)
        asr.setOnAsrTextListen(object : AsrEngine2.OnAsrTextListen {
            override fun onText(text: String) {
                Log.e("AudioRecon", text)
                if (progressDialog != null) {
                    runOnUiThread {
                        progressDialog?.setMessage(text)
                    }
                }
                runOnUiThread {
                    tvAsr.setText(text)
                }
                if (!isEventWord && (
                            text.contains("小克") ||
                                    text.contains("小可") ||
                                    text.contains("小刻") ||
                                    text.contains("小科") ||
                                    text.contains("小课") ||
                                    text.contains("小客") ||
                                    text.contains("小柯")
                            )) {
                    isEventWord = true
                    runOnUiThread {
                        progressDialog = ProgressDialog(this@HttpActivity)
                        progressDialog?.setMessage("等待您的指示....")
                        progressDialog?.show()
                        //打断TTS
                        tts?.stopEngineBtnClicked()
                        tts?.startEngineBtnClicked(eventWordAnswer)
                    }
                    //触发后停止录音
                    AudioRecognitionService.stop()
                    asr.stopfeedAudio()
                    asr.stopEngineBtnClicked()
                    asr.clearAsrTextListen()
                    asrResultText = ""
                    lastAsrText = ""
                    Thread{
                        Thread.sleep(2000)
                        runOnUiThread {
                            asr = AsrEngine2(SpeechEngineDefines.RECORDER_TYPE_RECORDER)
                            asr.start(this@HttpActivity)
                            asr.startEngineBtnClicked()


                            class MyCountDownTimer(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
                                override fun onTick(millisUntilFinished: Long) {
                                    count++
                                    if(count>=maxCount){
                                        asr.clearResultText()
                                        asr.stopEngineBtnClicked()
                                        this.cancel()
                                        count = 0
                                        runOnUiThread {
                                            isEventWord = false
                                            progressDialog?.dismiss()
                                            progressDialog = null
                                            if(asrResultText.trim().isEmpty()){
                                                tvLlmAsk.setText("你似乎没有发言")
                                            }else{
                                                tvLlmAsk.setText("提问:"+asrResultText)
                                            }

                                            eventLLmWord(asrResultText)
                                            startASrStream()
                                        }
                                    }else{
                                        runOnUiThread {
                                            if(progressDialog!=null && progressDialog!!.isShowing) {
                                                if(!lastAsrText.isEmpty()) {
                                                    progressDialog?.setMessage(lastAsrText + "(${maxCount - count})")
                                                }else{
                                                    progressDialog?.setMessage("请说出你想要的需求" + "(${maxCount - count})")
                                                }
                                            }
                                        }
                                    }
                                }
                                override fun onFinish() {
                                    // 倒计时结束时的操作
                                }
                            }
                            MyCountDownTimer(60000,1000).start()


                            asr.setOnAsrTextListen(object : AsrEngine2.OnAsrTextListen {
                                override fun onText(text: String) {
                                    Log.e("AudioRecon", text)
                                    if(!text.isEmpty()) {
                                        asrResultText = text
                                    }
                                    if(!lastAsrText.equals(asrResultText)) {
                                        count = 0
                                        lastAsrText = text
                                        runOnUiThread {
                                            if(progressDialog!=null && progressDialog!!.isShowing) {
                                                progressDialog?.setMessage(asrResultText+"(${maxCount-count})")
                                            }
                                        }
                                    }

                                }

                            })
                        }
                    }.start()


                }

            }
        })
        //录音
        AudioRecognitionService.start(this, object : AudioRecognitionService.ReadByteToListen {
            override fun read(audioData: ByteArray, size: Int) {
                Log.e("AudioRecon", "---->" + audioData.toString())
                asr.feedAudio(audioData, size)
            }

        })
        Log.e("TTsEngine", "Application becomming background.")
        asr.startEngineBtnClicked()
        if(tts==null){
            tts = TtsEngine2();
            tts!!.start(this)
            tts!!.switchEngine()
            tts!!.createConnection()
        }

    }

    private fun eventLLmWord(content: String) {
        if(content.trim().isEmpty()){
            tts?.startEngineBtnClicked(emptyWordAnswer)
        }else{
            HttpManager.httpLLM(content,{
                var result = it.choices[0].message.content
                Log.e("http", result)
                runOnUiThread {
                    tvLlm.setText("回答:"+result)
                    tts?.startEngineBtnClicked(result)
                }
            },{
                runOnUiThread {
                    tvLlm.setText(nullWordAnswer)
                    tts?.startEngineBtnClicked(nullWordAnswer)
//                    tvLlm.setText("error:"+it.toString())
                }
            })
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "Tts onDestroy")
        tts?.onDestroy()
        AudioRecognitionService.stop()
    }


}
